import axios from 'axios';
import qs from 'qs'
import { routerKey } from 'vue-router';
import router from '../router/index.js'
const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    baseURL: 'http://120.79.84.58/index.php/api',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
});

service.interceptors.request.use(
    config => {
        if (localStorage.getItem('token') != 'null' && localStorage.getItem('token')) {
            config.headers['token'] = localStorage.getItem('token')
        }
        if (
            config.data &&
            config.headers['Content-Type'] ===
              'application/x-www-form-urlencoded;charset=UTF-8'
          )
         config.data = qs.stringify(config.data)
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.data.code === 1) {
            return response.data;
        } else {
            if (response.data.msg == '尚未登陆，请登录后再试') {
                localStorage.setItem("ms_account", '');
                localStorage.setItem("token", '');
                router.push({path: '/login'})
            }
            return response.data;
        }
    },
    error => {
        return Promise.reject();
    }
);

export default service;
